/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.metis.document.parse.dialog.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import lombok.Getter;
import lombok.NonNull;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;

/**
 * Straight-forward implementation of interface {@link MultipartFile} where the file
 * data is held as a byte array in memory.
 */
@Getter
public class ByteArrayMultipartFile extends OutputStream implements MultipartFile {

    private final String name;

    private final String originalFilename;

    private final String contentType;

    @Override
    public void write(int b) {
        bos.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) {
        bos.write(b, off, len);
    }

    @NonNull
    ByteArrayOutputStream bos = new ByteArrayOutputStream();


    public ByteArrayMultipartFile(String name, String originalFilename, String contentType) {
        this.name = name;
        this.originalFilename = originalFilename;
        this.contentType = contentType;
    }

    @Override
    public boolean isEmpty() {
        return bos.size() == 0;
    }

    @Override
    public long getSize() {
        return bos.size();
    }

    @Override
    public byte @NotNull [] getBytes() throws IOException {
        return bos.toByteArray();
    }

    @Override
    public @NotNull InputStream getInputStream() {
        return new ByteArrayInputStream(bos.toByteArray());
    }

    @Override
    public void transferTo(@NotNull File destination) throws IOException {
        try (OutputStream outputStream = new FileOutputStream(destination)) {
            outputStream.write(bos.toByteArray());
        }
    }

    @Override
    public void write(byte @NotNull [] b) throws IOException {
        bos.write(b);
    }

    @Override
    public void flush() throws IOException {
        bos.flush();
    }

    @Override
    public void close() throws IOException {
        bos.close();
    }
}
